package com.ymatou.query.trading.api.testcase;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.query.trading.api.parameter.GetBuyerOrderListCountArguments;
import com.ymatou.query.trading.api.parameter.GetBuyerOrderListCountBean;
import com.ymatou.query.trading.api.parameter.GetBuyerOrderListCountResponse;
import com.ymatou.query.trading.api.parameter.ToBeEvaluatedOrdersCountArguments;
import com.ymatou.query.trading.api.service.GetBuyerOrderListCountCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.common.entitie.GetBuyerOrderListCountResult;
import com.ymttest.common.enums.OrderStatusEnum;
import com.ymttest.database.sqlwapper.YmtOrdersWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 获取用户订单数量 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_GetBuyerOrderListCount {
	private static GetBuyerOrderListCountBean gbolcbean;
	private static GetBuyerOrderListCountCall gbolccall;
	private static GetBuyerOrderListCountResponse response;
	private static YmtOrdersWapper ymtOrdersWapper;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("获取用户订单数量");
	}

	@Before
	public void caseUp() {
		gbolcbean = new GetBuyerOrderListCountBean();
		gbolccall = new GetBuyerOrderListCountCall();
		response = new GetBuyerOrderListCountResponse();
		ymtOrdersWapper = new YmtOrdersWapper();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(gbolccall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	@SuppressWarnings("unchecked")
	private void verifyResult() throws JSONException {
		ConstructExpectedData();
		DataUtil.verifyEquals(response.AllComplaintedCount,
				gbolccall.getAllComplaintedCount(), "验证AllComplaintedCount");
		DataUtil.verifyEquals(response.ToBeEvaluatedOrderCount,
				gbolccall.getToBeEvaluatedOrderCount(),
				"验证ToBeEvaluatedOrderCount");
		JSONObject AllRecordCountDic = gbolccall.getAllRecordCountDic();
		DataUtil.verifyEquals(response.AllRecordCountDic.size(),
				AllRecordCountDic.length(), "验证AllRecordCountDic的订单状态个数");
		Iterator<String> keys = AllRecordCountDic.keys();
		while (keys.hasNext()) {
			String status = keys.next();
			int count = AllRecordCountDic.getInt(status);
			DataUtil.verifyEquals(
					response.AllRecordCountDic.get(Integer.valueOf(status)),
					count, "验证状态为" + status + "的订单数量");
		}
	}

	private void ConstructExpectedData() {
		if (null == gbolcbean.getIsShangouOrder()
				&& gbolcbean.getIsGetComplaintedCount() == false
				&& DataUtil.isNullOrEmpty(gbolcbean.getOrderSources())
				&& DataUtil.isNullOrEmpty(gbolcbean.getOrderStatusList())
				&& gbolcbean.getBeginTime() == null
				&& gbolcbean.getEndTime() == null
				&& gbolcbean.getToBeEvaluatedDays() > 0) { // app端

			GetBuyerOrderListCountResult getBuyerOrderListCountResult = GetBuyerOrderListCountResultOfApp();
			ConstructResponseWithData(getBuyerOrderListCountResult);
			// ConstructResponse(); //代码更新的地方
		} else {
			ConstructResponse();
		}
	}

	@SuppressWarnings("rawtypes")
	private GetBuyerOrderListCountResult GetBuyerOrderListCountResultOfApp() {
		GetBuyerOrderListCountResult getBuyerOrderListCountResult = new GetBuyerOrderListCountResult();
		List<Map> tempOrderStatusCountInfos2 = new YmtOrdersWapper()
				.selectOrders2("o.iTradingStatus, count(o.iOrderId) as count",
						null,
						"o.itradingstatus in (1,2,3) and o.bDeleted is null and o.iUserId = "
								+ gbolcbean.getBuyerId()
								+ " group by o.iTradingStatus");
		for (int i = 0; i < tempOrderStatusCountInfos2.size(); i++) {
			Map OrderStatusCountInfo = tempOrderStatusCountInfos2.get(i);
			GetBuyerOrderListCountResult.OrderStatusCountInfo osci = new GetBuyerOrderListCountResult.OrderStatusCountInfo();
			osci.iTradingStatus = (int) OrderStatusCountInfo
					.get("iTradingStatus");
			osci.count = (int) OrderStatusCountInfo.get("count");
			getBuyerOrderListCountResult.OrderStatusCountInfos.add(osci);
		}

		return getBuyerOrderListCountResult;
	}

	private void ConstructResponse() {
		GetBuyerOrderListCountArguments args = new GetBuyerOrderListCountArguments();
		args.BuyerId = gbolcbean.getBuyerId();
		args.Shangou = gbolcbean.getIsShangouOrder();
		args.ShangouWithM2COrderCount = gbolcbean.isShangouWithM2COrderCount();
		args.OrderSources = gbolcbean.getOrderSources();
		args.From = gbolcbean.getBeginTime();
		args.To = gbolcbean.getEndTime();
		args.ReceivedStatus = gbolcbean.getIsGetComplaintedCount()
				? OrderStatusEnum.Received.getValue()
				: null;
		GetBuyerOrderListCountResult getBuyerOrderListCountResult = Execute(args);
		ConstructResponseWithData(getBuyerOrderListCountResult);
	}

	private int Execute(ToBeEvaluatedOrdersCountArguments args) {
		StringBuffer queryCondition = new StringBuffer();
		queryCondition.append(" iUserId = " + args.BuyerId);
		queryCondition.append(" and iTradingStatus = 4");
		queryCondition.append(" and bDeleted is null");
		queryCondition.append(" and isnull(bEvaluated,0) = 0");
		queryCondition.append(" and dConfirmedTime >= (getdate()-"
				+ args.ToBeEvaluatedDays + ")");
		if (null != args.Shangou && args.Shangou == true
				&& args.ShangouWithM2C == true) {
			queryCondition.append(" and bShangouOrder = 1");
		}

		return (int) ymtOrdersWapper
				.selectOrders2("count(*) as [ToBeEvaluatedOrderCount]", null,
						queryCondition.toString()).get(0)
				.get("ToBeEvaluatedOrderCount");
	}

	@SuppressWarnings("rawtypes")
	private List<Map> getAllStatusCount(GetBuyerOrderListCountArguments args) {
		List<Map> tempOrderStatusCountInfos1 = new ArrayList<Map>();
		if (null != args.Shangou && args.Shangou
				&& args.ShangouWithM2COrderCount) {
			StringBuffer queryCondition = new StringBuffer();
			queryCondition.append(" o.iUserId = " + args.BuyerId);
			queryCondition.append(" and o.bShangouOrder = 1");
			if (null != args.From) {
				queryCondition.append(" and o.dAddTime >= '" + args.From + "'");
			}
			if (null != args.To) {
				queryCondition.append(" and o.dAddTime ,= '" + args.To + "'");
			}
			queryCondition.append(" and o.bDeleted is null");
			queryCondition.append(" group by o.iTradingStatus, o.bPaidInFull");
			tempOrderStatusCountInfos1 = ymtOrdersWapper
					.selectOrders2(
							"o.iTradingStatus, o.bPaidInFull, count(o.iOrderId) as count",
							null, queryCondition.toString());
		} else {
			StringBuffer queryCondition = new StringBuffer();
			queryCondition.append(" o.iUserId = " + args.BuyerId);
			if (null != args.Shangou) {
				queryCondition.append(" and o.bShangouOrder = "
						+ DataUtil.bool2Int(args.Shangou));
			}
			if (null != args.From) {
				queryCondition.append(" and o.dAddTime >= '" + args.From + "'");
			}
			if (null != args.To) {
				queryCondition.append(" and o.dAddTime <= '" + args.To + "'");
			}
			if (null != gbolcbean.getOrderSources()) {
				queryCondition.append(" and ext.sOrderSource in "
						+ DataUtil.toInOfSql(args.OrderSources));
			}
			queryCondition.append(" and o.bDeleted is null");
			queryCondition.append(" group by o.iTradingStatus, o.bPaidInFull");
			tempOrderStatusCountInfos1 = ymtOrdersWapper
					.selectOrders2(
							"o.iTradingStatus, o.bPaidInFull, count(o.iOrderId) as count",
							" inner join Ymt_OrderExt as ext on ext.iOrderId = o.iOrderId ",
							queryCondition.toString());
		}
		return tempOrderStatusCountInfos1;
	}

	@SuppressWarnings("rawtypes")
	private GetBuyerOrderListCountResult Execute(
			GetBuyerOrderListCountArguments args) {
		GetBuyerOrderListCountResult getBuyerOrderListCountResult = new GetBuyerOrderListCountResult();

		List<Map> tempOrderStatusCountInfos1 = getAllStatusCount(args);
		for (int i = 0; i < tempOrderStatusCountInfos1.size(); i++) {
			Map OrderStatusCountInfo = tempOrderStatusCountInfos1.get(i);
			GetBuyerOrderListCountResult.OrderStatusCountInfo osci = new GetBuyerOrderListCountResult.OrderStatusCountInfo();
			osci.iTradingStatus = (int) OrderStatusCountInfo
					.get("iTradingStatus");
			osci.count = (int) OrderStatusCountInfo.get("count");
			osci.bPaidInFull = (Boolean) OrderStatusCountInfo
					.get("bPaidInFull");
			getBuyerOrderListCountResult.OrderStatusCountInfos.add(osci);
		}

		// @buyerReceivedStatus = ReceivedStatus
		Integer temp = null;
		if (null != args.ReceivedStatus) {
			StringBuffer queryCondition = new StringBuffer();
			queryCondition.append(" o.iUserId = " + args.BuyerId);
			queryCondition.append(" and o.iTradingStatus = "
					+ args.ReceivedStatus);
			queryCondition.append(" and o.iOrderId NOT IN (");
			queryCondition
					.append("select CAST (sTargetId AS INT) as iOrderId FROM Ymt_CreditDetail (nolock) WHERE iAction > - 1 and iUserId = "
							+ args.BuyerId);
			queryCondition.append(")");
			temp = (Integer) ymtOrdersWapper
					.selectOrders2("COUNT(iOrderId) AS complaintedCount", null,
							queryCondition.toString()).get(0)
					.get("complaintedCount");
		}
		getBuyerOrderListCountResult.ComplaintedCount = args.ReceivedStatus == null
				? null
				: temp;
		return getBuyerOrderListCountResult;
	}

	@SuppressWarnings("all")
	public void ConstructResponseWithData(GetBuyerOrderListCountResult data) {
		int total = 0;
		Map<Integer, Integer> all = new TreeMap<Integer, Integer>();

		if (null != data.OrderStatusCountInfos
				&& data.OrderStatusCountInfos.size() > 0) {
			int n;
			int sellerAcceptStatus = OrderStatusEnum.SellerAccept.getValue();
			int orderPostPayStatus = OrderStatusEnum.OrderPostPay.getValue();
			for (GetBuyerOrderListCountResult.OrderStatusCountInfo o : data.OrderStatusCountInfos) {
				if (o.iTradingStatus == sellerAcceptStatus) {
					if (o.bPaidInFull) {
						all.put(sellerAcceptStatus, o.count);
					} else {
						all.put(orderPostPayStatus, o.count);
					}
				} else {
					Integer value = all.get(o.iTradingStatus);
					if (null == value) {
						n = 0;
					} else {
						n = value;
					}
					all.put(o.iTradingStatus, n + o.count);
				}
				total += o.count;
			}
		}

		all.put(0, total);

		if (DataUtil.isNullOrEmpty(gbolcbean.getOrderStatusList()) == false) {
			gbolcbean.getOrderStatusList().forEach(a -> {
				if (!all.containsKey(a)) {
					all.put(a, 0);
				}
			});
		}

		response.AllRecordCountDic = all;
		response.AllComplaintedCount = data.ComplaintedCount;

		if (gbolcbean.getToBeEvaluatedDays() > 0) {
			ToBeEvaluatedOrdersCountArguments args = new ToBeEvaluatedOrdersCountArguments();
			args.BuyerId = gbolcbean.getBuyerId();
			args.Shangou = gbolcbean.getIsShangouOrder();
			args.ShangouWithM2C = gbolcbean.isShangouWithM2COrderCount();
			args.ToBeEvaluatedDays = gbolcbean.getToBeEvaluatedDays();
			response.ToBeEvaluatedOrderCount = Execute(args);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetBuyerOrderListCount_001() {
		Logger.start(true, "获取用户订单数量查询成功");
		try {
			int UserId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			// int BuyerId = 4425002;
			gbolcbean.setBuyerId(UserId);
			String date1 = YMTDateUtil.getBeforeOrNextDay(-10);
			String date2 = YMTDateUtil.getBeforeOrNextDay(1);
			// 查询开始时间
			Logger.comment("查询开始时间:" + date1);
			gbolcbean.setBeginTime(date1);
			// 查询结束时间
			Logger.comment("查询结束时间:" + date2);
			gbolcbean.setEndTime(date2);
			// 是否获待评价订单
			boolean IsGetComplaintedCount = true;
			Logger.comment("是否获待评价订单:" + IsGetComplaintedCount);
			gbolcbean.setIsGetComplaintedCount(IsGetComplaintedCount);
			// 是否获取闪购订单数量
			boolean IsShangouOrder = false;
			Logger.comment("是否获取闪购订单数量:" + IsShangouOrder);
			gbolcbean.setIsShangouOrder(IsShangouOrder);
			// 订单状态
			ArrayList<Integer> list = new ArrayList<Integer>();
			// list.add(4);
			gbolcbean.setOrderStatusList(list);
			// 发送请求
			gbolccall.setData(gbolcbean);
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			// Logger.verifyEquals(ErrorCode.SUCCESSMSG, gbolccall.getMsg(),
			// "验证Msg");
			verifyResult();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetBuyerOrderListCount_002() {
		Logger.start(true, "获取用户订单数量+待点评数量，查询成功");
		try {
			int UserId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			// int BuyerId = 4425002;
			gbolcbean.setBuyerId(UserId);
			String date1 = YMTDateUtil.getBeforeOrNextDay(-10);
			String date2 = YMTDateUtil.getBeforeOrNextDay(1);
			// 查询开始时间
			Logger.comment("查询开始时间:" + date1);
			gbolcbean.setBeginTime(date1);
			// 查询结束时间
			Logger.comment("查询结束时间:" + date2);
			gbolcbean.setEndTime(date2);
			// 是否获待评价订单
			boolean IsGetComplaintedCount = true;
			Logger.comment("是否获待评价订单:" + IsGetComplaintedCount);
			gbolcbean.setIsGetComplaintedCount(IsGetComplaintedCount);
			// 是否获取闪购订单数量
			boolean IsShangouOrder = false;
			Logger.comment("是否获取闪购订单数量:" + IsShangouOrder);
			gbolcbean.setIsShangouOrder(IsShangouOrder);
			// 订单状态
			ArrayList<Integer> list = new ArrayList<Integer>();
			list.add(18);
			gbolcbean.setOrderStatusList(list);
			// 发送请求
			gbolccall.setData(gbolcbean);
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			verifyResult();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetBuyerOrderListCount_003() {
		Logger.start(true, "获取用户闪购订单数量，查询成功");
		try {
			int BuyerId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			// int BuyerId = 216;
			gbolcbean.setBuyerId(BuyerId);
			String date1 = YMTDateUtil.getBeforeOrNextDay(-10);
			String date2 = YMTDateUtil.getBeforeOrNextDay(1);
			// 查询开始时间
			Logger.comment("查询开始时间:" + date1);
			gbolcbean.setBeginTime(date1);
			// 查询结束时间
			Logger.comment("查询结束时间:" + date2);
			gbolcbean.setEndTime(date2);
			// 是否获待评价订单
			boolean IsGetComplaintedCount = true;
			Logger.comment("是否获待评价订单:" + IsGetComplaintedCount);
			gbolcbean.setIsGetComplaintedCount(IsGetComplaintedCount);
			// 是否获取闪购订单数量
			boolean IsShangouOrder = true;
			Logger.comment("是否获取闪购订单数量:" + IsShangouOrder);
			gbolcbean.setIsShangouOrder(IsShangouOrder);
			// 订单状态
			ArrayList<Integer> list = new ArrayList<Integer>();
			list.add(18);
			gbolcbean.setOrderStatusList(list);
			// 发送请求
			gbolccall.setData(gbolcbean);
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			// Logger.verifyEquals(ErrorCode.SUCCESSMSG2, gbolccall.getMsg(),
			// "验证Msg");
			verifyResult();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetBuyerOrderListCount_004() {
		Logger.start(true, "获取用户闪购订单数量，查询成功");
		try {
			int BuyerId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			// int BuyerId = 216;
			gbolcbean.setBuyerId(BuyerId);
			String date1 = YMTDateUtil.getBeforeOrNextDay(-10);
			String date2 = YMTDateUtil.getBeforeOrNextDay(1);
			// 查询开始时间
			Logger.comment("查询开始时间:" + date1);
			gbolcbean.setBeginTime(date1);
			// 查询结束时间
			Logger.comment("查询结束时间:" + date2);
			gbolcbean.setEndTime(date2);
			// 是否获待评价订单
			boolean IsGetComplaintedCount = true;
			Logger.comment("是否获待评价订单:" + IsGetComplaintedCount);
			gbolcbean.setIsGetComplaintedCount(IsGetComplaintedCount);
			// 是否获取闪购订单数量
			boolean IsShangouOrder = true;
			Logger.comment("是否获取闪购订单数量:" + IsShangouOrder);
			gbolcbean.setIsShangouOrder(IsShangouOrder);
			// 订单状态
			ArrayList<Integer> list = new ArrayList<Integer>();
			list.add(19);
			gbolcbean.setOrderStatusList(list);
			// 发送请求
			gbolccall.setData(gbolcbean);
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			// Logger.verifyEquals(ErrorCode.SUCCESSMSG2, gbolccall.getMsg(),
			// "验证Msg");
			verifyResult();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetBuyerOrderListCount_005() {
		Logger.start(true, "app端用户查询，查询成功");
		try {
			int BuyerId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			gbolcbean.setBuyerId(BuyerId);
			int toBeEvaluatedDays = 60;
			gbolcbean.setToBeEvaluatedDays(toBeEvaluatedDays);
			// 发送请求
			gbolccall.setData(gbolcbean);
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			verifyResult();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetBuyerOrderListCount_006() {
		Logger.start(true, "app端用户查询，查询成功, 删除的订单不计数量");
		try {
			Logger.comment("准备一个状态为1的订单");
			OrderCallService orderCallService = new OrderCallService();
			PlaceOrderResp placeOrderResp = new OrderCallService()
					.createM2cOrder();

			int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			int sellerId = placeOrderResp.getOrderList().get(0).getSellerId();
			int userId = placeOrderResp.getUserId();
			Logger.comment("订单准备完成");

			gbolcbean.setBuyerId(userId);
			int toBeEvaluatedDays = 60;
			gbolcbean.setToBeEvaluatedDays(toBeEvaluatedDays);
			// 发送请求
			gbolccall.setData(gbolcbean);
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			int all = gbolccall.getAllRecordCountDic().getInt("0");
			int OrderEstablish = gbolccall.getAllRecordCountDic().getInt("1");

			Logger.comment("准备一个状态为1的订单, 并删除该订单");
			PlaceOrderResp placeOrderResp1 = new OrderCallService()
					.createM2cOrder();

			int orderId1 = placeOrderResp1.getOrderList().get(0).getOrderId();
			orderCallService.salesMarkOrderDeleted(orderId, userId, true);
			Logger.comment("订单准备完成");

			// 发送请求
			gbolccall.callService();
			Logger.comment("gbolccall send:" + gbolccall.getEntityString());
			Logger.comment("gbolccall response:" + gbolccall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS, gbolccall.getCode(), "验证Code");
			DataUtil.verifyEquals(all,
					gbolccall.getAllRecordCountDic().getInt("0"),
					"验证AllRecordCountDic.0");
			DataUtil.verifyEquals(OrderEstablish, gbolccall
					.getAllRecordCountDic().getInt("1"),
					"验证AllRecordCountDic.1");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}